const constants = require('../../../../common/Constants.js');
const umfDialog = require('../../../../utils/UmfDialog.js');
const netWork_utils = require('../../../../http/NetworkUtils.js');
import * as cacheUtils from '../../../../model/CacheUtils';
import * as umfToast from '../../../../utils/UmfToast';
var failUp = 0;
let cacheManager = null;
var app = getApp();
Page({
    data: {
        imgList: [],
        surplusImgs: 8,
        failUp: failUp,
        successUp: [],
        flag: 3,
        busiAgreement:[], //商户协议两张照片
     },
    onLoad: function (options) {

      cacheManager = new cacheUtils.cacheManager()
        .init("uploadPOSphoto" + options.storeId, constants.STORAGE_FUNC.POSPHOTO);
      let posPhotoCSData = cacheManager.getFunc();
      failUp = 0;
      let res = app.globalData.systemInfo
      let width = (res.screenWidth - 60) / 3
      let photoInfoData = JSON.parse(options.photoInfoData)
      for (let i = 0; i < photoInfoData.length; i++) {
        photoInfoData[i] = decodeURIComponent(photoInfoData[i])
      }
      this.setData({
        storeId: options.storeId,
        // surplusThisImgs: 19 - photoInfoData.length,
        surplusImgs: 8 - (posPhotoCSData.successUp ? posPhotoCSData.successUp.length:0),
        photoInfoData: photoInfoData,
        width: width,
        successUp: posPhotoCSData.successUp ? posPhotoCSData.successUp : [],
        imgList: posPhotoCSData.successUp ? posPhotoCSData.successUp : [],
        flag: posPhotoCSData.flag ? posPhotoCSData.flag : 3,
        busiAgreement: posPhotoCSData.busiAgreement ? posPhotoCSData.busiAgreement : initBusiAgree()
      })
    },
    complete: function () {
      let msg = _checkBusiAgree(this.data.busiAgreement)
        if (this.data.failUp > 0) {
            this.hasError();
        } else if (msg) {
            umfDialog.show(msg)
        } else {
            wx.navigateBack({
                delta: 1
            })
        }

    },
    
    previewExampleImg: function (e) {
      let item = e.currentTarget.dataset.current;
      wx.previewImage({
        current: item, // 当前显示图片的http链接
        urls: [item]// 需要预览的图片http链接列表      
      });
    },
    previewPreImg:function(e){
      let item = e.currentTarget.dataset.current;
      let that = this
      wx.previewImage({
        current: item, // 当前显示图片的http链接
        urls: that.data.photoInfoData // 需要预览的图片http链接列表       
      });
    },
    previewImg: function (e) {
        let item = e.currentTarget.dataset.current;
        let that = this;
        let urlList = [];
        for (let it in that.data.photoInfoData) {
          urlList.push(that.data.photoInfoData[it])
        }
        for (let ite in that.data.successUp) {
            urlList.push(that.data.successUp[ite].imgUrl)
        }        
        wx.previewImage({
            current: that.data.successUp[item].imgUrl, // 当前显示图片的http链接
            urls: urlList // 需要预览的图片http链接列表
        });
    },

    deleteImg: function (e) {
        let that = this
        let curr = e.currentTarget.id;
        wx.showModal({
            title: '提示',
            content: '是否删除该图片',
            success: function (res) {
                if (res.confirm) {
                  that._doDelete(curr)
                }
            }
        })
    },

    _doDelete:function(curr){
      let params={
        'storeId': this.data.storeId,
        'imgName': this.data.imgList[curr].imgName.toString()
      }
      let that = this
      netWork_utils.buildRequest(constants.Interfaces.FUNC_POS_DELETEIMG, params, {
        doHttpSucess: function (data) {
          if (constants.RetCodes.SUCCESS === data.retCode) {
            
              let imgList = that.data.imgList
              let successUp = that.data.successUp
              if (imgList[curr].imgState == 1) {
                failUp = that.data.failUp - 1
              } else {
                successUp.splice(curr, 1)
                for (let i = curr; i < successUp.length; i++) {
                  successUp[i].imgTag = i
                }
              }
              imgList.splice(curr, 1)
              for (let i = curr; i < imgList.length; i++) {
                imgList[i].imgTag = i
              }
              that.setData({
                successUp: successUp,
                imgList: imgList,
                failUp: failUp,
                surplusImgs: that.data.surplusImgs + 1
              })

              cacheManager.cacheFunc({ successUp: successUp, })
              umfToast.showToast("已删除该照片")
            return true;
          }
          return false;

        }
      }).send();
    },

    isLoading: function () {
        let msg = "图片正在上传中，请等待上传完成";
        umfDialog.show(msg, this, false)
    },

  
    addPhoto: function () {
      if (this.data.failUp == 0 && this.data.imgList.length > this.data.successUp.length){
        this.isLoading()
      } else if (this.data.failUp > 0){
        this.hasError()
      }else {
        let that = this
        wx.chooseImage({
          count: this.data.surplusImgs, // 默认9
          sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: (res) => {
            // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
            let i = 0;//第几个
            _upload(that, res.tempFilePaths, i)

          }
        })
      }
        
    },
    hasError: function () {
        umfDialog.showAll("有" + this.data.failUp + "张图片上传失败，是否重新上传", "是", "否", () => {
            //否
        }, () => {
            //重新上传
            failUp = 0;
            let failUrlList = [];
            for (let ite in this.data.imgList) {
                if (this.data.imgList[ite].imgState == 1)
                    failUrlList.push(this.data.imgList[ite].imgUrl)
            }
            this.setData({
                failUp: failUp
            })
            let i = 0;
            _upload(this, failUrlList, i)
        })
    },
    addBusiAgree:function(e){
      let busiTag = e.currentTarget.id;
      var that =this
      wx.chooseImage({
        count: 1,
        sizeType: ['compressed'], //压缩图
        success: function (res) {
          let tempFilePaths = res.tempFilePaths;
          uploadBusiAgree(that,busiTag,that.data.busiAgreement,tempFilePaths[0]);
        }
      });
    },
    busiHasErr:function(e){
      let busiTag = e.currentTarget.id;
      umfDialog.showAll( "抱歉,图片上传失败", "重试", "重新选择", () => {
        //否
        this.addBusiAgree(e)
      }, () => {
            //重新上传
        uploadBusiAgree(this, busiTag, this.data.busiAgreement, this.data.busiAgreement[busiTag].imgUrl)
      })
    }
});
//Q4商户协议照片信息
function initBusiAgree() {
  //imgState: 0 上传中  1成功  2 失败  3 还未上传
  let busiAgreement = []
  let busiAgreeBaseInfo = { "tag":0,"imgName":"baseImg","name": "商户协议-基本信息页","imgState":3, 
  "imgUrl":"","imgRemoteUrl":"",
  "exampleUrl": "https://m.soopay.net/c/static/tozogssx" }
  busiAgreement.push(busiAgreeBaseInfo)
  let busiAgreeStamp = {
    "tag": 1, "imgName": "stampImg","name": "商户协议-盖章页", "imgState": 3,
    "imgUrl": "", "imgRemoteUrl": "",
    "exampleUrl": "../../../../icons/example_stamp.png" }
  busiAgreement.push(busiAgreeStamp)
  return busiAgreement
}
function _upload(page, filePaths, i) {
    let length = filePaths.length;//待上传图片总个数
    let imgList = page.data.imgList
    //重传之前失败的
    if (imgList.length > page.data.successUp.length + failUp) {
        imgList[page.data.successUp.length + i].imgState = 0
    } else {//上传新的照片
      let successUp = page.data.successUp;
      let imgName = 1
      if (page.data.failUp != 0 && successUp.length != 0){
        imgName = successUp[successUp.length + page.data.failUp- 1].imgName + 1
      }else if (successUp.length != 0) {
        imgName = successUp[successUp.length - 1].imgName+1
      }
      imgList.push({ 'imgName':imgName,imgUrl: filePaths[i], imgTag: imgList.length, imgState: 0})
    }
    page.setData({
        imgList: imgList,
        // surplusImgs: page.data.surplusThisImgs - page.data.imgList.length
        surplusImgs: page.data.surplusImgs - 1
    })
    let posImg = 'posImg' + imgList[i].imgTag
    netWork_utils.buildRequest(constants.Interfaces.FUNC_OPENPOS_UPLOAD, {
      'storeId': page.data.storeId, 'imgName': imgList[imgList.length - 1].imgName.toString()
    }, {
        doHttpSucess: function (response) {
            if (constants.RetCodes.SUCCESS === response.retCode) {
                //上传成功
                let successUp = page.data.successUp;
                let imgName = 1
                if (successUp.length != 0) {
                  imgName = successUp[successUp.length - 1].imgName + 1
                }
                successUp.push({
                    // imgName: imgName,
                    imgUrl: filePaths[i],
                    imgTag: successUp.length,
                    imgState: 2,
                    imgRemoteUrl: response.imgUrl,
                    imgName:imgName
                })
                imgList[successUp.length - 1].imgState = 2
                page.setData({
                    // flag: 4,
                    successUp: successUp,
                    imgList: imgList
                })
                cacheManager.cacheFunc({successUp: successUp})
                return true;
            }
            imgList[imgList.length - 1].imgState = 1;
            failUp++;
            page.setData({
                failUp: failUp,
                imgList: imgList
            });
            return false;
        },
        doHttpFailure: function (erroData) {
          umfDialog.show("上传失败，请重新上传")
            //上传失败
            if (imgList.length > page.data.successUp.length + failUp) {
                imgList[page.data.successUp.length + i].imgState = 1
            } else {
                imgList[imgList.length - 1].imgState = 1;
            }
            failUp++;
            page.setData({
                failUp: failUp,
                imgList: imgList
            });
            return true
        },
        doComplete: function () {
            i++;
            if (i == length) {
            } else {
                _upload(page, filePaths, i, length)
            }
            return false;
        }
    }, false).upload(filePaths[i]);
}

function uploadBusiAgree(page,busiTag,busiAgreement,filepath){
  busiAgreement[busiTag].imgState = "0"
  busiAgreement[busiTag].imgRemoteUrl=""
  busiAgreement[busiTag].imgUrl = filepath
  page.setData({
    busiAgreement: busiAgreement
  })
  netWork_utils.buildRequest(constants.Interfaces.FUNC_OPENPOS_UPLOAD, {
    'storeId': page.data.storeId, 'imgName': busiAgreement[busiTag].imgName
  }, {
      doHttpSucess: function (response) {
        if (constants.RetCodes.SUCCESS === response.retCode) {
          //上传成功
          busiAgreement[busiTag].imgState = "1"
          busiAgreement[busiTag].imgRemoteUrl = response.imgUrl
          page.setData({
            busiAgreement: busiAgreement
          })
          //flag判断
          if (!_checkBusiAgree(busiAgreement)) {
            page.setData({
              flag:4
            })
            
          }else {
            page.setData({
              flag: 1  //不完整
            })
          }
          cacheManager.cacheFunc({ busiAgreement: busiAgreement, flag: page.data.flag })
          return
        }
        busiUplodFail(page, busiAgreement, busiTag, filepath)
      },
      doHttpFailure: function (erroData) {
        busiUplodFail(page, busiAgreement, busiTag, filepath)
      },
      doComplete: function () {},
  },false).upload(filepath)
}

function busiUplodFail(page, busiAgreement, busiTag,filepath){
  busiAgreement[busiTag].imgState = "2"
  busiAgreement[busiTag].imgRemoteUrl = ""
  busiAgreement[busiTag].imgUrl = filepath
  page.setData({
    busiAgreement: busiAgreement
  })
}
function _checkBusiAgree(busiAgreement){
  let msg = ""
      for(let i=0;i<busiAgreement.length;i++){
        if(busiAgreement[i].imgState == 0){
          msg = busiAgreement[i].name + "正在上传，请等待上传完成"
          return msg
        } else if (busiAgreement[i].imgState == 2) {
          msg = busiAgreement[i].name + "上传失败，请重新上传"
          return msg
        } else if (busiAgreement[i].imgState == 3) {
          msg = "请上传"+busiAgreement[i].name 
          return msg
        } 
      }
      return msg
}